<template>
    <!-- 查询区域 -->
    <div style="">
        <a-modal v-model:open="deleteOpen" title="删除提示" ok-text="确认" cancel-text="取消" @ok="deleteOk">
            确认删除？
        </a-modal>
        <a-modal v-model:open="deleteConfirmOpen" title="删除提示" ok-text="确认" cancel-text="取消" @ok="deleteConfirmOk">
            有用户设置了该角色,确认删除？
        </a-modal>
        <a-modal v-model:open="addOpen" v-model:title="addModifyTitle" :footer="null" :afterClose="afterCloseModal">
            <a-form ref="formRef" :model="role" :label-col="labelCol" :wrapper-col="wrapperCol" @finish="onFinish" :rules="roleRules"
                @finishFailed="onFinishFailed">
                <input type="hidden" name="id" v-model="role.id" />
                <a-form-item label="角色名称" name="authority">
                    <!--修改角色时,账号不能修改-->
                    <a-input v-model:value="role.authority" />
                </a-form-item>
                <a-form-item label="角色显示名称" name="displayName">
                    <a-input v-model:value="role.displayName" />
                </a-form-item>
                <a-form-item :wrapper-col="{ span: 14, offset: 4 }">
                    <a-button type="primary" html-type="submit">保存</a-button>
                    <a-button style="margin-left: 10px" @click="closeForm">关闭</a-button>
                </a-form-item>
            </a-form>
        </a-modal>
        <a-modal v-model:open="permissionOpen" title="设置角色目录" @ok="handleAttachPermissionOk" width="700px"
            :afterClose="afterClosePermissionModal">
            <a-table :columns="permissionColumns" :pagination="false" :data-source="permissionTabledata"
                :customRow="permissionRowClick" :row-selection="permissionRowSelection" :scroll="{ y: 300 }" bordered>
                <template #bodyCell="{ column, record }">
                    <template v-if="column.dataIndex === 'operation'">
                        <a-checkbox-group v-if="record.pid" v-model:value="record.operation" style="width: 100%"
                            @click.stop>
                            <a-row>
                                <a-col :span="8">
                                    <a-checkbox value="1">新增</a-checkbox>
                                </a-col>
                                <a-col :span="8">
                                    <a-checkbox value="2">修改</a-checkbox>
                                </a-col>
                                <a-col :span="8">
                                    <a-checkbox value="4">删除</a-checkbox>
                                </a-col>
                            </a-row>
                        </a-checkbox-group>
                        <span v-else></span>

                    </template>
                </template>
            </a-table>
        </a-modal>
        <a-row>
            <a-col :span="24">
                <a-form layout="inline">
                    <a-form-item label="角色名称">
                        <a-input placeholder="输入角色名称模糊查询" v-model:value="queryParam.authority" />
                    </a-form-item>
                    <a-form-item label="角色显示名称">
                        <a-input placeholder="输入角色显示名称模糊查询" v-model:value="queryParam.displayName" />
                    </a-form-item>
                    <a-space wrap>
                        <a-button type="primary" @click="searchQuery">查询</a-button>
                        <a-button type="primary" @click="searchReset">重置</a-button>
                    </a-space>
                </a-form>
            </a-col>
        </a-row>
    </div>

    <!-- 操作按钮区域 -->

    <div class="table-operator" style="margin:5px 0;border-top: 5px;float: left; ">
        <a-space wrap>
            <a-button @click="handleAdd" type="primary">添加角色</a-button>
            <a-button @click="handleModify" type="primary">修改角色</a-button>
            <a-button @click="handleDelete" type="primary">删除角色</a-button>
            <a-button @click="attachPermission" type="primary">配置目录</a-button>
        </a-space>
    </div>
    <div style="margin:5px 0;padding:5px 0;">
        <a-table bordered class="ant-table-striped"
            :row-class-name="(_record: any, index: any) => (index % 2 === 1 ? 'table-striped' : null)" :columns="columns"
            :loading="loading" :rowSelection="{ selectedRowKeys, onChange: onSelectChange }" :dataSource="tabledata"
            :pagination="ipagination" :scroll="{}" :customRow="rowClick" @change="handleTableChange">

        </a-table>
    </div>
</template>
   
<script lang="ts" setup>
import {
    ref,
    reactive,
    onMounted,
    Ref
} from "vue";
import type { UnwrapRef } from 'vue';
import { message } from 'ant-design-vue';
import http from '@/utils/http';
import showErrors from '@/utils/publicfunction';
import type { Data } from '@/utils/http';



/**
 * 角色对象数据类型定义
 * id
 * authority 角色名称，有唯一约束，不能重复 ROLE_USER  ROLE_ADMIN等
 * displayName 角色显示名称 普通用户，管理员等
 */
interface FormState {
    id: number;
    authority: string;
    displayName: string;
}

//列表数据类型定义
interface ColumnProp extends FormState {
    key: number;
}

//分页组件
interface PaginationProp {
    current: number;
    pageSize: number;
    total: number;
    showSizeChanger: boolean;
    showQuickJumper: boolean;
    pageSizeOptions: string[];
    showTotal: (total: number, range: number[]) => string;
}

//列表数据变量定义
const tabledata: Ref<ColumnProp[]> = ref([]);
//列表的表头定义
const columns = [
    { title: "角色名称", dataIndex: "authority" },
    { title: "角色显示名称", dataIndex: "displayName" }
];

const loading = ref(false);
//查询参数定义
const queryParam = reactive({
    authority: "",
    displayName: ""
});

//列表选择的数据的key列表
const selectedRowKeys: Ref<number[]> = ref([]);
//列表选择的数据整行值列表
let selectionRows: ColumnProp[] = [];

//行点击事件,record参数为该行的整行值
const rowClick = (record: ColumnProp, index: number) => {
    return {
        //单击事件
        onClick: (event: MouseEvent) => {
            // const computedSelectedRowKeys = computed(() => selectedRowKeys.value)
            //   .value;
            //如果该行已经被选择，取消选择
            if (selectedRowKeys.value.includes(record.id)) {
                //过滤掉该行的key
                selectedRowKeys.value = selectedRowKeys.value.filter(function (
                    val,
                    index,
                    arr
                ) {
                    return val != record.id;
                });
                //过滤掉该行的数据整行值
                selectionRows = selectionRows.filter(function (
                    val,
                    index,
                    arr
                ) {
                    return val.id != record.id;
                });
            } else {
                //如果该行没有被选择，则进行选择，selectedRowKeys是响应数据，添加数据就是选择了行
                selectedRowKeys.value.push(record.id);
                selectionRows.push(record);
                // console.log('push length'+selectionRows.value.length)
            }
        }
    };
};
//分页栏数据
const ipagination: Ref<PaginationProp> = ref({
    //hideOnSinglePage:true,//只有一页时是否隐藏分页器
    current: 0,
    pageSize: 8,
    total: 0,
    showSizeChanger: true,
    showQuickJumper: true,
    pageSizeOptions: ["8", "10", "20"], //这里注意只能是字符串，不能是数字
    showTotal: (total: number, range: number[]) =>
        `显示${range[0]}-${range[1]}条，共有 ${total}条`,
});
// const generateData = (n: number, pageSize: number) => {
//   const result: ColumnProp[] = [];
//   for (let i = 0; i < pageSize; i++) {
//     result.push({
//       key: i + pageSize * n,
//       idcard: i + pageSize * n,
//       name: `Edward King ${i + pageSize * n}`,
//       age: 32,
//       sex: i % 2,
//       mobile: "13555555",
//     });
//   }
//   return result;
// };

//执行查询公用方法
const executeQuery = (pageParam: Data) => {
    loading.value = true;

    http.get('/role/page', pageParam).then((res) => {
        loading.value = false;
        if (res.data.status === "success") {
            tabledata.value = res.data.businessData.pageData;
            ipagination.value.total = res.data.businessData.total;
        }
        else {
            message.error(res.data.businessData.errMsg);
        }
    })
    //重置key值的数组
    selectedRowKeys.value = [];
    //重置选择的数据值的数组
    selectionRows = [];
}
//查询按钮事件
const searchQuery = () => {
    ipagination.value.current = 1;
    const pageParam = {
        pageNo: 0,
        pageSize: ipagination.value.pageSize,
        authority: queryParam.authority,
        displayName: queryParam.displayName

    }
    //执行查询公用方法
    executeQuery(pageParam);
};
//重置按钮事件
const searchReset = () => {
    queryParam.authority = "";
    queryParam.displayName = "";
};


//点击每列左边的checkbox后的事件
const onSelectChange = (
    pselectedRowKeys: number[],
    pselectionRows: ColumnProp[]
) => {
    selectedRowKeys.value = pselectedRowKeys;
    selectionRows = pselectionRows;
};

//页码改变的回调，参数是改变后的页码及每页条数
const handleTableChange = (
    pagination: PaginationProp,
    filters: any,
    sorter: any
) => {
    //页码改变的回调，参数是改变后的页码及每页条数
    // console.log(pagination)
    // console.log(filters)
    // console.log(sorter)
    ipagination.value.current = pagination.current;
    const pageParam = {
        pageNo: ipagination.value.current - 1,
        pageSize: ipagination.value.pageSize,
        authority: queryParam.authority,
        displayName: queryParam.displayName
    }
    //执行查询公用方法
    executeQuery(pageParam);
};



/******新增角色*********/
//角色对象数据变量定义
const role: UnwrapRef<FormState> = reactive({
    id: 0,
    authority: "",
    displayName: ""
});

//form的校验规则
const roleRules = {
    authority: [
        {
            required: true,
            message: "角色名为必填项！",
            trigger: "blur",
        },
        {
            max: 20,
            message: "角色名长度不得超过20！",
            trigger: "blur",
        },
        {
            pattern: /^ROLE_[a-zA-Z0-9]{1,15}$/,
            message: '角色名必须以ROLE_开头',
            trigger: "blur",
        },
        {
            // 异步验证 多了一个callback函数
            //橘色名称不能重复
            validator: (rule: any, val: any, callback: any) => {
                if (val.length > 0) {
                    const rolenameParam = {
                        rolename: val,
                        id: role.id
                    };
                    // 这里进行异步操作,下面以promise举例
                    http.get('/role/validateRolename', rolenameParam).then((res) => {
                        if (res.data.status === "success") {
                            callback()
                        }
                        else {
                            callback(new Error('角色名称不能重复'))
                        }
                    })
                } else {
                    callback()
                }
            },
            trigger: "blur"
        }
    ],
    displayName: [
        {
            required: true,
            message: "角色显示名为必填项！",
            trigger: "blur",
        },
        {
            max: 20,
            message: "角色显示名长度不得超过20！",
            trigger: "blur",
        }
    ]
};

//重置角色对象数据
const clearRole = () => {
    role.id = 0;
    role.authority = "";
    role.displayName = "";
};
//设置角色对象数据
const setRole = () => {
    role.id = selectionRows[0].id;
    role.authority = selectionRows[0].authority;
    role.displayName = selectionRows[0].displayName;
};
//form中label宽度
const labelCol = { style: { width: '150px' } };
const wrapperCol = { span: 14 };
//打开或关闭角色form窗口
const addOpen = ref<boolean>(false);
//窗口title
const addModifyTitle = ref<string>("新增角色");
//是否改动角色账号，新增时可修改，修改角色数据时，账号不能修改
const disabledFlag = ref<boolean>(false);
const formRef = ref();

//关闭窗口
const closeForm = () => {
    //关闭窗口
    addOpen.value = false;
}

//窗口关闭后清除校验信息
const afterCloseModal = () => {
    formRef.value.clearValidate();
}

//新增角色按钮点击事件
const handleAdd = () => {
    //重置角色数据
    clearRole();
    //修改title
    addModifyTitle.value = "新增角色";
    //新增可以修改账号
    disabledFlag.value = false;
    //打开窗口
    addOpen.value = true;

};


//校验成功后提交form
const onFinish = (values: any) => {
    let url = '/role/addRole';
    //如果id不为0，则为修改数据，走修改数据的url
    if (role.id != 0) {
        url = '/role/modifyRole';
    }
    http.post(url, role).then((res) => {
        if (res.data.status === "success") {
            message.success("保存成功!");
            //关闭窗口
            addOpen.value = false;

            //刷新列表
            const pageParam = {
                pageNo: ipagination.value.current - 1,
                pageSize: ipagination.value.pageSize,
                authority: queryParam.authority,
                displayName: queryParam.displayName
            }
            //执行查询公用方法
            executeQuery(pageParam);
        }
        else {
            showErrors(res.data.businessData);            
        }
    })

};

const onFinishFailed = (errorInfo: any) => {
    console.log('Failed:', errorInfo);
};
/******新增角色结束*********/

/******修改角色*********/
//修改按钮点击事件
const handleModify = () => {
    //如果选择了一条数据
    if (selectionRows.length == 1) {
        //设置角色数据
        setRole();
        //设置窗口title
        addModifyTitle.value = "修改角色";
        //账号不可修改
        disabledFlag.value = true;

        //打开窗口
        addOpen.value = true;
    } else {
        message.info("请选择一条数据!");
    }
};
/******修改角色结束*********/

/******删除角色*********/
//删除提示框显示变量
const deleteOpen = ref<boolean>(false);
//角色关联了用户，确认model提示框显示变量
const deleteConfirmOpen = ref<boolean>(false);

//删除按钮点击事件
const handleDelete = () => {
    //判断是否选择了数据
    if (selectedRowKeys.value.length == 0) {
        message.info("请选择数据");
        return;
    }
    //显示删除数据提示框
    deleteOpen.value = true;
};

//确定删除
const deleteOk = () => {
    //关闭提示框
    deleteOpen.value = false;
    //要删除的数据参数
    const deleteParam = {
        ids: selectedRowKeys.value
    }
    //校验角色是否被用户关联
    http.get('/role/findUserCountByRoleIds', deleteParam).then((res) => {
        if (res.data.status === "success") {
            const result = res.data.businessData;
            //如果已经关联了，则弹出提示框
            if (result > 0) {
                deleteConfirmOpen.value = true;
            } else {
                //没有关联，则删除
                executeDeleteRole();
            }
        }
        else {
            message.error(res.data.businessData.errMsg);
        }
    });
};

//角色关联了用户，确认删除的方法
const deleteConfirmOk = () => {
    //关闭提示框
    deleteConfirmOpen.value = false;
    executeDeleteRole();
};

//执行删除角色
const executeDeleteRole = () => {
    //要删除的数据参数
    const deleteParam = {
        ids: selectedRowKeys.value
    };
    //删除
    http.delete('/role/delete', selectedRowKeys.value).then((res) => {
        if (res.data.status === "success") {
            //刷新列表
            const pageParam = {
                pageNo: ipagination.value.current - 1,
                pageSize: ipagination.value.pageSize,
                authority: queryParam.authority,
                displayName: queryParam.displayName
            }
            //执行查询公用方法
            executeQuery(pageParam);
        }
        else {
            message.error(res.data.businessData.errMsg);
        }
    })
}
/******删除角色结束*********/

/******给角色配置目录*********/
const permissionOpen = ref<boolean>(false);
/**
 * 提交给后端的目录修改数据类型定义
 * roleId: 角色id
 * permissionId 目录id
 * operation  操作属性,查看是必须的，0只有查看权限，1增加，2修改，
 * 4删除，3增加修改，5增加删除，6修改删除，7增加修改删除
 * databaseOperation 数据库操作属性,方便前端批量提交，0新增，1修改，2删除
  */
interface CommitData {
    roleId: number;
    permissionId: number;
    operation: number;
    databaseOperation: number;
}
//设置完成后点击确定事件
const handleAttachPermissionOk = (
) => {
    //已经选择的整行数据列表
    let newPermissionSelectionRows: DataItem[] = [];
    //在选择的数据中，如果一级目录的子目录没有全部选中，该一级目录是不会被选中的
    //但是在角色配置时，是需要被选中的，此变量就是需要选中又没有被选中的一级目录的
    //id，由于可能重复，所以用set
    const firstId: Set<number> = new Set();
    permissionSelectionRows.map(v => {
        //有父目录且没有被选中
        if (v.pid && !permissionSelectedRowKeys.value.includes(v.pid)) {
            firstId.add(v.pid);
        }
        newPermissionSelectionRows.push(v);
    });
    //将需要选中又没有被选中的一级目录的整行数据处理
    firstId.forEach(v => {
        newPermissionSelectionRows.push(getFirstMenuById(v));
    });

    //新选择的数据的长度
    const nl = newPermissionSelectionRows.length;
    //旧的数据长度
    const ol = permissionOlddata.length;
    //所有需要提交的数据变量
    const allData: CommitData[] = [];
    let j = 0;
    // 新增数据
    for (let i = 0; i < nl; i++) {
        j = 0;
        for (; j < ol; j++) {
            if (newPermissionSelectionRows[i].id == permissionOlddata[j].id) {
                break;
            }
        }
        if (j == ol) {
            let operationData = 0;
            if (newPermissionSelectionRows[i].pid) {
                const operationArr: string[] = newPermissionSelectionRows[i].operation as string[];
                operationArr.map(v => {
                    operationData += parseInt(v);
                })
            }
            allData.push(
                {
                    roleId: selectedRowKeys.value[0],
                    permissionId: newPermissionSelectionRows[i].id,
                    operation: operationData,
                    databaseOperation: 0
                }
            );
        }
    }
    // 删除数据
    for (let i = 0; i < ol; i++) {
        j = 0;
        for (; j < nl; j++) {
            if (permissionOlddata[i].id == newPermissionSelectionRows[j].id) {
                break;
            }
        }
        if (j == nl) {
            //删除的数据，operation直接给0
            allData.push(
                {
                    roleId: selectedRowKeys.value[0],
                    permissionId: permissionOlddata[i].id,
                    operation: 0,
                    databaseOperation: 2
                }
            );
        }
    }
    //修改的数据
    newPermissionSelectionRows.map(nv => {
        permissionOlddata.map(ov => {
            if (nv.id == ov.id && nv.pid) {
                const operationArr: string[] = nv.operation as string[];
                let operationData = 0;
                //console.log("233333333333333333333333333333333")
                operationArr.map(v => {
                    operationData += parseInt(v);
                })

                allData.push(
                    {
                        roleId: selectedRowKeys.value[0],
                        permissionId: nv.id,
                        operation: operationData,
                        databaseOperation: 1
                    }
                );

            }
        })
    });
    // console.log("addDataaddDataaddDataaddDataaddDataaddDataaddDataaddData")
    // console.log(allData)

    if (allData.length > 0) {
        //设置
        http.post('/role/attachPermissionToRole', allData).then((res) => {
            if (res.data.status === "success") {
                message.success("设置目录成功");
                permissionOpen.value = false;
            }
            else {
                message.error(res.data.businessData.errMsg);
            }
        })

    } else {
        permissionOpen.value = false;
    }
};

//设置目录的表列定义
const permissionColumns = [
    {
        title: '目录名称',
        dataIndex: 'permissionName',
        key: 'permissionName',
    },
    {
        title: '显示名称',
        dataIndex: 'displayName',
        key: 'displayName'
    },
    {
        title: '操作属性',
        dataIndex: 'operation',
        key: 'operation'
    }

];

//用户对象数据类型定义
interface DataItem {
    id: number;
    pid?: number;
    permissionName: string;
    displayName: string;
    orderNumber: number;
    operation?: number | string[];
    key: number;
    children?: DataItem[];
}
//目录列表数据
const permissionTabledata: Ref<DataItem[]> = ref([]);
//列表选择的数据的key列表
const permissionSelectedRowKeys: Ref<number[]> = ref([]);
//列表选择的数据整行值列表
let permissionSelectionRows: DataItem[] = [];
//列表选择的原始数据整行值列表
let permissionOlddata: DataItem[] = [];

//根据获取id获取父目录整行数据
const getFirstMenuById = (id: number): DataItem => {
    let result: DataItem = {
        id: 0,
        permissionName: "",
        displayName: "",
        orderNumber: 0,
        operation: 0,
        key: 0
    };
    const filterResult = permissionTabledata.value.filter(v => {
        return v.id == id;
    });
    filterResult.length && (result = filterResult[0]);
    return result;
}

//设置角色目录窗口关闭后事件
const afterClosePermissionModal = () => {
    //列表数据
    permissionTabledata.value = [];
    //列表选择的数据的key列表
    permissionSelectedRowKeys.value = [];
    //列表选择的数据整行值列表
    permissionSelectionRows = [];
    //列表选择的原始数据整行值列表
    permissionOlddata = [];
}
//行点击事件,record参数为该行的整行值
const permissionRowClick = (record: DataItem, index: number) => {
    return {
        //单击事件
        onClick: (event: MouseEvent) => {
            //如果该行已经被选择，取消选择
            if (permissionSelectedRowKeys.value.includes(record.id)) {
                //过滤掉该行的key
                permissionSelectedRowKeys.value = permissionSelectedRowKeys.value.filter(function (
                    val,
                    index,
                    arr
                ) {
                    if (record.pid) {
                        //如果选择的是二级目录，过滤掉该目录和该目录的上级目录id
                        //把操作属性栏的checkbox全部取消掉
                        record.operation = [];
                        return val != record.id && val != record.pid;
                    } else {
                        //如果是一级目录，获取该目录的整行数据
                        const result = getFirstMenuById(record.id);
                        //获取子目录
                        const children = result.children as DataItem[];
                        //该目录下是否有子目录被选中的变量
                        let checked = false;
                        //该目录下有子目录被选中则过滤掉
                        for (let i = 0; i < children.length; i++) {
                            if (val == children[i].id) {
                                //将数据的操作属性置为0，效果是操作属性的checkbox都没有被选择
                                children[i].operation = [];
                                checked = true;
                                break;
                            }
                        }
                        //该目录下有子目录被选中则过滤掉
                        if (checked) {
                            return !checked;
                        }
                        //过滤本行的数据的id
                        return val != record.id;
                    }
                });
                //过滤掉该行的数据整行，逻辑与上面相同，只是数据为整行
                permissionSelectionRows = permissionSelectionRows.filter(function (
                    val,
                    index,
                    arr
                ) {
                    if (record.pid) {
                        return val.id != record.id && val.id != record.pid;
                    } else {
                        //该行为一级目录
                        const result = getFirstMenuById(record.id);
                        //取消选择该目录下的所有子目录
                        const children = result.children as DataItem[];
                        let checked = false;
                        for (let i = 0; i < children.length; i++) {
                            if (val.id == children[i].id) {
                                checked = true;
                                break;
                            }
                        }
                        if (checked) {
                            return !checked;
                        }
                        return val.id != record.id;
                    }
                });

                // console.log("permissionSelectedRowKeys.value1111111111111111111111")
                // console.log(permissionSelectedRowKeys.value)
            } else {
                //如果该行没有被选择，则进行选择，permissionSelectedRowKeys是响应数据，添加数据就是选择了行
                permissionSelectedRowKeys.value.push(record.id);
                //console.log(permissionSelectionRows)
                //选择该行则操作属性都被选中
                record.operation = ['1', '2', '4'];
                //整行数据
                permissionSelectionRows.push(record);

                //如果有子目录，则子目录要全部选择
                let result = getFirstMenuById(record.id);
                result.children?.map(c => {
                    //如果曾经没有被选中，则push
                    if (!permissionSelectedRowKeys.value.includes(c.id)) {
                        permissionSelectedRowKeys.value.push(c.id);
                        //子目录操作属性都被选中
                        c.operation = ['1', '2', '4'];
                        permissionSelectionRows.push(c);
                    }
                });

                //如果子目录全部选择，则父目录也要被选择
                const pid = record.pid;
                if (pid) {
                    //已经被选中的key长度
                    const sl = permissionSelectedRowKeys.value.length;
                    //获取父目录数据
                    result = getFirstMenuById(pid);
                    //父目录下的所有子目录数据
                    const children = result.children as DataItem[];
                    //子目录数据长度
                    const cl = children.length;

                    let j = 0;
                    let count = 0;
                    // 新增数据
                    for (let i = 0; i < sl; i++) {
                        j = 0;
                        //该父目录下是否所有子目录都被选中
                        for (; j < cl; j++) {
                            if (permissionSelectedRowKeys.value[i] == children[j].id) {
                                count++;
                            }
                        }

                    }
                    //该父目录下所有子目录都被选中,添加父目录
                    if (count == cl) {
                        permissionSelectedRowKeys.value.push(pid);
                        permissionSelectionRows.push(result);
                    }
                }

                //   selectionRows.push(record);
                //   console.log("permissionSelectedRowKeys.value1222222222222222222222222222")
                //   console.log(permissionSelectedRowKeys.value)
                // console.log('push length'+selectionRows.value.length)
            }
        }
    };
};

const permissionRowSelection = ref({
    hideDefaultSelections: true,
    selectedRowKeys: permissionSelectedRowKeys,
    checkStrictly: false,
    onChange: (ppermissionSelectedRowKeys: number[], pselectedRows: DataItem[]) => {
        // console.log("onchange---------------------------------")
        // console.log(`permissionSelectedRowKeys: ${ppermissionSelectedRowKeys}`, 'selectedRows: ', pselectedRows);
        // console.log("onchange---------------------------------")
        permissionSelectedRowKeys.value = ppermissionSelectedRowKeys;
        permissionSelectionRows = pselectedRows;
        //   selectionRows = pselectedRows;
    },
    onSelect: (record: DataItem, selected: boolean, selectedRows: DataItem[]) => {
        if (selected) {
            //被选中状态
            if (record.pid) {
                //二级目录
                record.operation = ['1', '2', '4'];
            } else {
                //一级目录
                const firstMenu = getFirstMenuById(record.id);
                firstMenu.children?.map(c => {
                    //如果曾经没有被选中
                    if (!permissionSelectedRowKeys.value.includes(c.id)) {
                        c.operation = ['1', '2', '4'];
                    }
                });
            }
        } else {
            //非选中状态
            if (record.pid) {
                //二级目录
                record.operation = [];
            } else {
                //一级目录
                const firstMenu = getFirstMenuById(record.id);
                firstMenu.children?.map(c => {
                    //所有子目录清除操作属性
                    c.operation = [];
                });
            }
        }
    },
});

//执行查询公用方法
const permissionExecuteQuery = (queryParam: Data) => {
    http.get('/role/getAllPermission', queryParam).then((res) => {
        if (res.data.status === "success") {
            //目录数据列表
            permissionTabledata.value = res.data.businessData.permissionList;
            //已经被选中的目录数据id
            let recievedList = res.data.businessData.checkedList as number[];
            //在组件中，如果父目录下的子目录没有全部选中，则该父目录是不被选中的
            //而传过来的数据是被选中的，所以要做相应的处理
            recievedList = recievedList.filter(v => {
                let firstMenu = getFirstMenuById(v);
                //如果为父目录，找得到数据即为父目录
                if (firstMenu) {
                    //找到子目录
                    const children = firstMenu.children as DataItem[];
                    if (!children || children.length == 0) {
                        return true;
                    }
                    //子目录长度
                    const childrenSize = children.length;
                    //子目录被选中的数据长度
                    let attachSize = 0;
                    children.map((cv) => {
                        if (cv.operation != null) {
                            attachSize++;
                        }
                    });
                    //如果相等则保留
                    if (childrenSize == attachSize) {
                        return true;
                    } else {
                        //如果不相等，则将父目录整行数据放在原始数据中
                        permissionOlddata.push(firstMenu);
                        //剔除已经选中状态
                        return false;
                    }
                } else {
                    //如果不为父目录则保留
                    return true;
                }
            });

            //重置key值的数组
            permissionSelectedRowKeys.value = recievedList;

            permissionTabledata.value.map(fv => {
                //如果key值被选中，则整行值放在permissionSelectionRows数组中
                if (permissionSelectedRowKeys.value.includes(fv.id)) {
                    //已经被选中的初始数据
                    permissionSelectionRows.push(fv);
                    //原始数据
                    permissionOlddata.push(fv);
                }
                //子目录的操作属性
                const children = fv.children as DataItem[];
                children.map(v => {
                    if (v.operation) {
                        if (v.operation == 1) {
                            v.operation = ['1'];
                        } else if (v.operation == 2) {
                            v.operation = ['2'];
                        } else if (v.operation == 3) {
                            v.operation = ['1', '2'];
                        } else if (v.operation == 4) {
                            v.operation = ['4'];
                        } else if (v.operation == 5) {
                            v.operation = ['1', '4'];
                        } else if (v.operation == 6) {
                            v.operation = ['2', '4'];
                        } else if (v.operation == 7) {
                            v.operation = ['1', '2', '4'];
                        }
                    } else {
                        //如果操作属性为0
                        v.operation = [];
                    }
                    //如果key值被选中，则整行值放在permissionSelectionRows数组中
                    if (permissionSelectedRowKeys.value.includes(v.id)) {
                        permissionSelectionRows.push(v);
                        //原始数据整行值
                        permissionOlddata.push(v);
                    }
                })

            })
            // console.log("permissionOlddatapermissionOlddatapermissionOlddatapermissionOlddatapermissionOlddata")
            // console.log(permissionOlddata)

        }
        else {
            message.error(res.data.businessData.errMsg);
        }
    })

    //重置选择的数据值的数组
    // selectionRows = [];
}
//配置目录按钮点击事件
const attachPermission = () => {
    //如果选择了一条数据
    if (selectionRows.length == 1) {
        //打开窗口
        permissionOpen.value = true;

        const queryParam = {
            roleId: selectedRowKeys.value[0]
        }
        //执行查询公用方法
        permissionExecuteQuery(queryParam);
    } else {
        message.info("请选择一条数据!");
    }
}


/******给角色配置目录结束*********/
//页面加载完成后，刷新第一页数据
onMounted(() => {
    //如果table设置了 :scroll="{ x: 1500 }"，则要先给个数据，否则报错
    tabledata.value = [{
        "id": 1,
        "authority": "ROLE_ADMIN",
        "displayName": "超级管理员",
        "key": 1
    }];
    tabledata.value = [];
    ipagination.value.current = 1;
    const pageParam = {
        pageNo: 0,
        pageSize: ipagination.value.pageSize,
        authority: "",
        displayName: ""
    }
    //执行查询公用方法
    executeQuery(pageParam);
});

</script>
<style scoped>
/*[data-doc-theme='light'] */
.ant-table-striped :deep(.table-striped) td {
    background-color: #fafafa;
}

[data-doc-theme='dark'] .ant-table-striped :deep(.table-striped) td {
    background-color: rgb(29, 29, 29);
}
</style>